<template>
    <div class=''>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <div :class="{ 'transition':true,' maxHeight':showSearch ,'minHeight':!showSearch}">
            <el-card>
                <el-row :gutter="10" class="mb8">
                    <el-form  label-width="68px" :inline="true">
                        <el-form-item label="用户名称" prop="userName">
                            <el-input placeholder="请输入用户名称" clearable size="small" style="width: 240px"/>
                        </el-form-item>
                        <el-form-item label="手机号码" prop="phonenumber">
                            <el-input placeholder="请输入手机号码" clearable size="small" style="width: 240px"/>
                        </el-form-item>
                        <el-form-item label="状态" prop="status">
                            <el-select placeholder="用户状态" clearable size="small" style="width: 240px">             
                            </el-select>
                         </el-form-item>
                        <el-form-item label="创建时间">
                          <el-date-picker           
                            size="small"
                            style="width: 240px"
                            value-format="yyyy-MM-dd"
                            type="daterange"
                            range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                          ></el-date-picker>
                        </el-form-item>
                        <el-form-item>            
                            <el-button type="primary" icon="el-icon-search" size="mini" round>搜索</el-button>
                            <el-button  type="warning" icon="el-icon-refresh" size="mini" round>重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-row>          
            </el-card>
        </div>

        <!-- 卡片视图区域 -->
        <!-- :style="'height:'+ windowHeight" -->
        <el-card>  
             
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" v-hasPermi="['system:user:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" v-hasPermi="['system:user:edit']" >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" v-hasPermi="['system:user:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="el-icon-upload2" size="mini" v-hasPermi="['system:user:import']">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" v-hasPermi="['system:user:export']" >导出</el-button>
          </el-col>
            <right-toolbar class="right-toolbar" :showSearch.sync="showSearch" @queryTable="getUserList" :columns="columns"></right-toolbar>
        </el-row>

              <el-table
                :data="usersList"
                border
                style="width: 100%; font-size: 14px"
                >
                <el-table-column fixed type="selection" width="40"/>
                <el-table-column prop="userId" label="用户ID" v-if="columns[0].visible"/>
                <el-table-column prop="username" label="用户名" v-if="columns[1].visible"/>
                <el-table-column prop="jobNumber" label="工号" sortablev-if="columns[2].visible"/>
                <el-table-column prop="email" label="邮箱" v-if="columns[3].visible"/>
                <el-table-column prop="mobile" label="电话" v-if="columns[4].visible"/>
                <el-table-column prop="role_name" label="角色" v-if="columns[5].visible"/>
                <el-table-column
                  label="状态"
                  v-if="columns[6].visible">
                    <template slot-scope="scope">
                        <el-switch v-model="status" @change="userStateChanged(scope.row)"></el-switch>
                    </template>
                </el-table-column>

                <el-table-column prop="createTime" label="创建时间" sortable v-if="columns[7].visible"/>
                <el-table-column
                  fixed="right"
                  label="操作" >
                  <template slot-scope="scope" >
                     <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)" circle></el-button>
                     <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row)" circle></el-button>
                     <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                        <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)" circle></el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>  
              <el-pagination
                 @size-change="handleSizeChange"
                 @current-change="handleCurrentChange"
                :current-page="queryInfo.page"
                :page-sizes="[10, 20, 50, 100, 999]"
                :page-size="queryInfo.limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="toral">
              </el-pagination>           
        </el-card>        

        <!-- 添加用户的对话框 -->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="30%" @close="addDialogClosed" :close-on-click-modal="false" :close-on-press-escape="false">
           <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                     <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="工号" prop="jobNumber">
                     <el-input v-model="addForm.jobNumber"></el-input>
                </el-form-item>               
                <el-form-item label="邮箱" prop="email">
                     <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                     <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>

           </el-form>

            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改用户的对话框 -->
        <el-dialog title="修改用户信息" :visible.sync="updateDialogVisible" @close="editDialogClosed" width="30%" :close-on-click-modal="false" :close-on-press-escape="false">
           <el-form :model="updateForm" :rules="addFormRules" ref="updateFormRef" label-width="70px">
                <el-form-item label="用户名">
                     <el-input v-model="updateForm.username" :disabled="true"></el-input>
                </el-form-item>
                 <el-form-item label="工号">
                     <el-input v-model="updateForm.jobNumber" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                     <el-input v-model="updateForm.email"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                     <el-input v-model="updateForm.mobile"></el-input>
                </el-form-item>
           </el-form>

            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="updateDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分配角色的对话框 -->
        <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" @close="roleDialogClosed" width="30%" :close-on-click-modal="false" :close-on-press-escape="false">
           <el-form :model="userInfo">
                <el-form-item label="用户名">
                     <el-input v-model="userInfo.username" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="当前的角色" prop="email">
                     <el-input v-model="userInfo.role_name" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="分配新角色" prop="mobile">
                    <template>
                        <el-select v-model="selectRoleId" placeholder="请选择">
                            <el-option v-for="item in roleInfo" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
                        </el-select>
                    </template>
                </el-form-item>
           </el-form>

            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRole">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>
<script>
export default {
    name: '',
    data () {
        // 验证邮箱的规则
        var checkEmail = (rule, value, cb) => {
            const regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
            if (regEmail.test(value)) {
                return cb()
            }
            cb(new Error('请输入合法的邮箱'))
        }

         // 验证手机号码的规则
        var checkMobile = (rule, value, cb) => {
            const regMobile = /^[1][3,4,5,7,8][0-9]{9}$/
            if (regMobile.test(value)) {
                return cb()
            }
            cb(new Error('请输入合法的手机号码'))
        }

        return {
            // windowHeight: (document.documentElement.clientHeight * 0.82) + 'px',   //实时屏幕高度
            queryInfo: {
                query: '',
                // 当前页数
                page: 1,
                // 当前每页显示多少条数据
                limit: 10
            },
            // 用户数据信息
            usersList: [],            
            // 总共有多少条数据
            toral: 0,
            addDialogVisible: false,
            updateDialogVisible: false,
            setRoleDialogVisible: false,
            addForm: {
                username: '',
                jobNumber: '',
                password: '123456',
                email: 'Test@yeah.net',
                mobile: ''
            },
            updateForm: { },
            addFormRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 5 个字符', trigger: 'blur' }
                 ],
                jobNumber: [
                    { required: true, message: '请输入工号', trigger: 'blur' }                  
                 ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                 ],
                mobile: [
                    { required: true, message: '请输入电话', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                 ]
            },
            // 需要分配角色的用户信息
            userInfo: {},
            // 所有角色的数据
            roleInfo: [],
            // 新的角色数据
            selectRoleId: '',
            status:true,
            // 列信息
            columns: [
              { key: 0, label: `用户ID`, visible: true },
              { key: 1, label: `用户名`, visible: true },
              { key: 2, label: `工号`, visible: true },
              { key: 3, label: `邮箱`, visible: true },
              { key: 4, label: `电话`, visible: true },
              { key: 5, label: `角色`, visible: true },
              { key: 6, label: `状态`, visible: true },
              { key: 7, label: `创建时间`, visible: true }
            ],
            showSearch: true,            
        }
    },
    watch: {
    },
    created () {
        this.getUserList()
    },    
    methods: {
        async getUserList () {
           await this.$http.get('/sys/user/list', { params: this.queryInfo }).then(({ data:res })=>{
               if (res.code !== 2000) return this.$message.error(res.meta.msg)
               this.usersList = res.data.page.list
               console.log(this.usersList)
               this.toral = res.data.page.totalCount
           }).catch(err=>{
               return this.$message.error(err)
           })          
        },
        // 用户状态改变
        async userStateChanged (userinfo) {
            const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
            if (res.meta.status !== 200) {
                userinfo.mg_state = !userinfo.mg_state
                return this.$message.error('更新用户信息失败!')
            }
            this.$message.success('更新用户信息成功!')
        },
        // 编辑用户
        async showEditDialog (user) {           
            this.updateForm = user
            this.updateDialogVisible = true
        },
        // 删除用户
        deleteUser (usreinfo) {          
                this.$confirm(`确认删除"${usreinfo.username}"用户信息, 是否继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {              
                 console.log(this.deleteUserInfo)
                await this.$http.delete('/sys/user/delete', {data: [usreinfo.userId]}).then(({ data:res }) =>{                                 
                    if (res.code !== 2000) {
                        return this.$message.error(res.msg)              
                    }else{
                        this.getUserList()
                        this.$message.success('用户删除成功!')
                        this.addDialogVisible = false   
                    } 
                }).catch(err=>{
                    console.log(err)
                })
             })               
        },
        // 打开用户角色对话框
        async setRole (userinfo) {
            this.userInfo = userinfo
            // 在展示对话框之前，获取所有角色的列表
            const { data: res } = await this.$http.get('roles')
            if (res.meta.status !== 200) return this.$message.error('获取角色失败')
            this.roleInfo = res.data
            this.setRoleDialogVisible = true
        },
        // 给用户分配角色
        async editRole () {
             const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { id: this.userInfo.id, rid: this.selectRoleId })
            if (res.meta.status !== 200) return this.$message.error('修改用户角色失败' + res.meta.msg)
            this.setRoleDialogVisible = false
            this.getUserList()
            this.$message.success('用修改用户角色成功!')
        },
        // 监听分配角色对话框的关闭事件
        roleDialogClosed () {
            this.roleInfo = []
            this.userInfo = []
            this.selectRoleId = ''
        },
        // 监听 pagesize 改变的事件
        handleSizeChange (newSize) {
            this.queryInfo.limit = newSize
            this.getUserList()
        },
        // 监听页码值改变事件
        handleCurrentChange (newPage) {
             this.queryInfo.page = newPage
            this.getUserList()
        },
        // 监听添加用户对话框的关闭事件
        addDialogClosed () {
            this.$refs.addFormRef.resetFields()
        },
        // 添加用户
        addUser () {
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) return 
                 await this.$http.post('/sys/user/regis', this.getData(this.addForm)).then(response =>{
                    const res = response.data                 
                    if (res.code !== 2000) {
                        return this.$message.error(res.msg)              
                    }else{
                        this.getUserList()
                        this.$message.success('用户添加成功!')  
                        this.addDialogVisible = false   
                    } 
                }).catch(error =>{
                    console.log('请求失败'+error) 
                })                
            })           
        },
        editDialogClosed () {
            this.$refs.updateFormRef.resetFields()
        },
        editUser () {
            this.$refs.updateFormRef.validate(async valid => {               
                if (valid) { 
                    await this.$http.put('/sys/user/update', this.updateForm).then(({ data:res }) =>{  
                        console.log(res)                      
                        if (res.code !== 2000) {
                            return this.$message.error('用户修改失败')            
                        }else{
                            this.getUserList()
                            this.$message.success('用户修改成功!')
                            this.updateDialogVisible = false   
                        } 
                    }).catch(error =>{
                        console.log('请求失败'+error) 
                    })  
                } 
            })
        },
        getData(dataObj) {
            /* json格式提交： */       
            return JSON.stringify(dataObj)
      }
    }
}
</script>

<style scoped>

  .minHeight{
    height: 0px;
  }

  .maxHeight{
    height: 82px;
  }

 .transition { 
  transition: height .5s ease;
  overflow: hidden;
}

</style>
